require 'date'

class GameController < ApplicationController
     
     def cents_to_s(c)
          "#{c/100}.#{(c/10)%10}#{c%10}"
     end
     
     def overview  
          @quickWatch = self.getWatchedStocks(@current_user.id)
          self.changeQuickwatch if request.post? and params['symbol']
          @m = Match.find_by_id(params[:id])
          @startingmoney = @m.startmoney.truncate
          redirect_to dash_url if @m == nil

          @current_um = nil
          
          @m.users_matches.each do |um|
               if um.user_id == @current_user.id then
                    @current_um = um
                    break
               end
          end
          
          redirect_to dash_url if @current_um == nil

          @title = @m.title
          @current_um.updateCapital
          @total = @current_um.capital

          #finished game
          if @m.finished then
               @endTimeDisplay = (@m.begintime + @m.timealloted.days()).strftime("%m/%d/%Y @ %I:%M%p")
               @beforeAfter = 1

          #unstarted game 
          elsif @m.pending then
               self.join if request.post?

               @gameJoined = @current_um.joined
               @beginTimeDisplay = (Time.now + 1.day()).strftime("%m/%d/%Y @ %I:%M%p") #TODO
               @beforeAfter = -1

          #current game
          else
               if not @m.started
                    @m.started = true
                    @m.dropUnjoined
               end
               
               @change = @current_um.change
               self.transact if request.post?

               @portfolio = [{'symbol'=>'Cash', 'price'=>100, 'shares'=> self.cents_to_s(@current_um.money)}]
               @current_um.stocks.each do |sym, h|
                    if h['previousClose']>h['price']
                         change = "loss"
                    elsif h['previousClose'] < h['price']
                         change = "gain"
                    else
                         change = "nochange"
                    end
                    
                    @portfolio << {'symbol' => sym, 'price' => h['price'],
                         'shares' => h['shares'], 'change'=>change}
               end

               @timeLeft = @m.timeLeft      
               @beforeAfter = 0
          end

          @membersOfGame = []
          @leaders = []
          
          for um in @m.users_matches.order(capital: :desc) do
               um.updateCapital unless @m.finished
               @leaders << {'name' => um.user.username, 'score' => um.capital, 'change'=>um.change}
               @membersOfGame << um.user.username
          end

          @quickWatch = getWatchedStocks(@current_user.id)

     end


     def join
          @current_um.joined = true
          @current_um.save
     end


     def transact  #assume post request
          #check that params exist
          unless params['tradeQuantity'] and params['tradeSymbol'] and params['buyorsell'] then
               return [params.to_s]
          end

          #grab 'em
          qty = params['tradeQuantity'].to_i
          sym = (sanitize params['tradeSymbol']).upcase
          
          return [params.to_s] unless params['buyorsell'] == 'Sell' or params['buyorsell'] == 'Buy'
          
          buy = params['buyorsell'] == 'Buy'

          #check their validity
          unless qty > 0 and qty.to_s == params['tradeQuantity'] then
               @errors << "Quantity must be a positive integer"
          end
          
          quote = self.getQuote( sym ) if sym != ""
          
          if quote == nil then
               @errors << "Please enter a valid stock symbol" 
               return @errors
          end

          #check that they are consistent with current portfolio
          price = quote[:price].to_i
          @errors << "You don't have enough money" if price*qty > @current_um.money and buy
          
          if !buy then
               if @current_um.stocks[sym] == nil then
                    @errors << "You don't have stock in #{sym}"
               elsif @current_um.stocks[sym]['shares'] < qty then
                    @errors << "You don't have that much to sell"
               end
          end

          return @errors if @errors.length > 0

          qty *= -1 unless buy

          @current_um.changeStock(sym, qty, price)
          @current_um.save
          return []
     end


     def new
          if request.post? then
               unless params['gamelength'] and params['startingmoney'] and params['name'] and
                         params['invite0'] and params['startTime'] and params['name'] != "" then
                    @errors << "please fill in all fields"
                    return
               end

               if params['gamelength'].to_i.to_s != params['gamelength'] or 
                         params['gamelength'].to_i <= 0 then
                    
                    @errors << "please enter a positive integer for game length" 
               end

               if params['startingmoney'].to_i.to_s != params['startingmoney'] or
                         params['startingmoney'].to_i <= 0 then
                    
                    @errors << "please enter a positive integer for starting money"
               end

               if sanitize(params['name']) != params['name'] then
                    @errors << "name must not contain special characters"
               end

               unless params['startTime']
                    @errors << "that is not a valid date"
               end

               unames = []
               i = 0
               
               while params.has_key? ('invite' + i.to_s) do
                    unames << params['invite' + i.to_s]
                    i += 1
               end

               players = []
               
               for uname in unames do
                    user = User.find_by_username(sanitize uname)
                    
                    if user == nil then
                         @errors << "#{sanitize uname} isn't a valid username"
                    elsif
                         players << user
                    end
               end

               for player in players do
                    unless Friend.find_by(user_id: @current_user.id, friend_id: player.id) then
                         @errors << "you aren't friends with #{player.username}" 
                    end
               end

               startdate = Date.parse params['startTime']
               
               if startdate <= Date.today
                    @errors << "please pick a future date"
               end

               if @errors == [] then
                    m = Match.new
                    m.title = sanitize params['name']
                    m.startmoney = params['startingmoney'].to_i*100
                    m.owner = @current_user.id
                    m.timealloted = params['gamelength'].to_i
                    m.begintime = startdate
                    m.save
                    
                    for player in players do
                         UsersMatch.create(match_id: m.id, user_id: player.id, joined: false,
                                           money: m.startmoney, stocks: {}).updateCapital
                    end
                    
                    UsersMatch.create(match_id: m.id, user_id: @current_user.id,
                                      joined: true, money: m.startmoney, stocks: {}).updateCapital
                    redirect_to dash_url
               end
          end
     end
end
